//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang -cc1 functionality, which implements the
// core compiler functionality along with a number of additional tools for
// demonstration and testing purposes.
//
//===----------------------------------------------------------------------===//

#include "llvm/Option/Arg.h"
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h"
#include "clang/FrontendTool/Utils.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
//qali-add
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/helper.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdio>
using namespace clang;
using namespace llvm::opt;
using namespace std;

//qali-add
namespace feature {
	struct CodeFeature {
		union {
			int iValue;
			double dValue;
		};
		string szDesc;

	public:
		CodeFeature(int i, string desc) { iValue = i; szDesc = desc; }
		CodeFeature(double d, string desc) { dValue = d; szDesc = desc; }
	};

	static CodeFeature Feature_n(0, "5.Halstead: Total operators + operands");
	static CodeFeature Feature_v(0.0, "6. Halstead: Volume");
	static CodeFeature Feature_l(0.0, "7. Halstead: program length");
	static CodeFeature Feature_d(0.0, "8. Halstead: difficulty");
	static CodeFeature Feature_e(0.0, "9. Halstead: effort");
	static CodeFeature Feature_t(0.0, "12. Halstead: time estimator");
	static CodeFeature Feature_uniqOp(0, "17. Halstead: unique operators");
	static CodeFeature Feature_uniqOpnd(0, "18. Halstead: unique operands");
	static CodeFeature Feature_Ops(0, "19. Halstead: total operators");
	static CodeFeature Feature_Opnds(0, "20. Halstead: totoal operands");
	static CodeFeature Feature_branch(0, "21. branch count of the flow graph");

	ofstream commentFileO;
	void init(string szFile) {
		string cName = szFile + ".comment";
		commentFileO.open(cName.c_str(), ios_base::binary);
	}
	void finalize()
	{
		commentFileO.close();
	}
}
void DumpF(feature::CodeFeature &cf, ostream &os, bool i);
//===----------------------------------------------------------------------===//
// Main driver
//===----------------------------------------------------------------------===//

static void LLVMErrorHandler(void *UserData, const std::string &Message,
                             bool GenCrashDiag) {
  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);

  Diags.Report(diag::err_fe_error_backend) << Message;

  // Run the interrupt handlers to make sure any special cleanups get done, in
  // particular that we remove files registered with RemoveFileOnSignal.
  llvm::sys::RunInterruptHandlers();

  // We cannot recover from llvm errors.  When reporting a fatal error, exit
  // with status 70 to generate crash diagnostics.  For BSD systems this is
  // defined as an internal software error.  Otherwise, exit with status 1.
  exit(GenCrashDiag ? 70 : 1);
}

#ifdef LINK_POLLY_INTO_TOOLS
namespace polly {
void initializePollyPasses(llvm::PassRegistry &Registry);
}
#endif

int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
  std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());

  // Register the support for object-file-wrapped Clang modules.
  auto PCHOps = Clang->getPCHContainerOperations();
  PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
  PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());

  // Initialize targets first, so that --version shows registered targets.
  llvm::InitializeAllTargets();
  llvm::InitializeAllTargetMCs();
  llvm::InitializeAllAsmPrinters();
  llvm::InitializeAllAsmParsers();

#ifdef LINK_POLLY_INTO_TOOLS
  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
  polly::initializePollyPasses(Registry);
#endif

  // Buffer diagnostics from argument parsing so that we can output them using a
  // well formed diagnostic object.
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
  bool Success = CompilerInvocation::CreateFromArgs(
      Clang->getInvocation(), Argv.begin(), Argv.end(), Diags);

  //qali-add: init
  string szInput = Clang->getFrontendOpts().Inputs.front().getFile();
  string szOutput = Clang->getFrontendOpts().OutputFile;
  feature::init(szInput);


  // Infer the builtin include path if unspecified.
  if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
      Clang->getHeaderSearchOpts().ResourceDir.empty())
    Clang->getHeaderSearchOpts().ResourceDir =
      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);

  // Create the actual diagnostics engine.
  Clang->createDiagnostics();
  if (!Clang->hasDiagnostics())
    return 1;

  // Set an error handler, so that any LLVM backend diagnostics go through our
  // error handler.
  llvm::install_fatal_error_handler(LLVMErrorHandler,
                                  static_cast<void*>(&Clang->getDiagnostics()));

  DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
  if (!Success)
    return 1;

  // Execute the frontend actions.
  Success = ExecuteCompilerInvocation(Clang.get());
  

  //qali-add: dumping the stats for program 
  using namespace feature;
  Feature_n.iValue = feature::N1 + feature::N2;

  feature::mu1 = feature::mu1_funcs.size() + feature::mu1_ops.size();
  feature::mu2 = feature::mu2_ints.size() + feature::mu2_ptrs.size() + feature::mu2_odds;
  int mu = feature::mu1 + feature::mu2;
  Feature_v.dValue = Feature_n.iValue * log2(mu);

  double vStar = (2 + mu2_prime) * log2(2 + mu2_prime);
  Feature_l.dValue = vStar / Feature_n.iValue;
  Feature_d.dValue = Feature_n.iValue / vStar;

  Feature_uniqOp.iValue = mu1;
  Feature_uniqOpnd.iValue = mu2;
  Feature_Ops.iValue = feature::N1;
  Feature_Opnds.iValue = feature::N2;
  Feature_branch.iValue = feature::branchCount;
  Feature_e.dValue = Feature_v.dValue / Feature_l.dValue;
  Feature_t.dValue = Feature_e.dValue / 18;

  unsigned int version = Clang->getInvocation().getDiagnosticOpts().ErrorLimit;
  if (version == 0)
	  version = 1;
  stringstream ss;
  ss << version;
  string szVersion;
  ss >> szVersion;
  string szFileID = szInput + szVersion; 
  
  ofstream outf;
  outf.open(szOutput.c_str(), std::ofstream::app);
  outf.precision(5);
  //outf.width(18);
  //outf.fill(' ');
  outf.unsetf(std::ios::floatfield);

  outf << szFileID << ",";
  DumpF(Feature_n, outf, 1);
  DumpF(Feature_v, outf, 0);
  DumpF(Feature_l, outf, 0);
  DumpF(Feature_d, outf, 0);
  DumpF(Feature_e, outf, 0);
  DumpF(Feature_t, outf, 0);
  DumpF(Feature_uniqOp, outf, 1);
  DumpF(Feature_uniqOpnd, outf, 1);
  DumpF(Feature_Ops, outf, 1);
  DumpF(Feature_Opnds, outf, 1);
  DumpF(Feature_branch, outf, 1);  
  outf << endl;


  feature::finalize();
  outf.close();


  // If any timers were active but haven't been destroyed yet, print their
  // results now.  This happens in -disable-free mode.
  llvm::TimerGroup::printAll(llvm::errs());

  // Our error handler depends on the Diagnostics object, which we're
  // potentially about to delete. Uninstall the handler now so that any
  // later errors use the default handling behavior instead.
  llvm::remove_fatal_error_handler();

  // When running with -disable-free, don't do any destruction or shutdown.
  if (Clang->getFrontendOpts().DisableFree) {
    if (llvm::AreStatisticsEnabled() || Clang->getFrontendOpts().ShowStats)
      llvm::PrintStatistics();
    BuryPointer(std::move(Clang));
    return !Success;
  }

  // Managed static deconstruction. Useful for making things like
  // -time-passes usable.
  llvm::llvm_shutdown();

  return !Success;
}

void DumpF(feature::CodeFeature &cf, ostream &os, bool i)
{
	//os << (i ? cf.iValue : cf.dValue) << "\t\t\t" << cf.szDesc << endl;
	os << (i ? cf.iValue : cf.dValue) << ",";
}

